<?php

namespace App\Console\Commands\System\NSQ;


use App\Enums\Common\NsqEnum;
use App\Models\System\SystemNotifyCenterModel;
use App\Service\System\SystemNotifyService;
use Illuminate\Console\Command;
use Illuminate\Support\Facades\Log;
use Illuminate\Support\Facades\Validator;
use Kuafu\Nsq\NsqSubscriber;
use NSQClient\Contract\Message;

class NsqSubSystemPopWindowCommand extends Command
{
    protected $signature = 'system:nsq-sub-pop-window';

    protected $description = 'NSQ订阅 - 商家app弹窗订阅';

    public function handle()
    {
        (new NsqSubscriber(config('nsq.default.address')))
            ->sub(NsqEnum::TOPIC_SYSTEM_POP_WINDOW, NsqEnum::CHANNEL_TIGER_SYSTEM_POP_WINDOW,
                function (Message $message) {

                    // debug
                    if (isTest()) {
                        dump($message->data());
                    }

                    $data = $message->data();

                    Log::info("NsqSubSystemPopWindowCommand in:", $data);

                    // 参数校验
                    if (!$this->valid($data)) {
                        $message->done();
                        return;
                    }

                    $this->doHandle($message->data());

                    $message->done();
                });
    }

    private function valid(array $data): bool
    {
        $validator = Validator::make($data, [
            'title'        => 'required|string',
            'type'         => 'required|integer',
            'target'       => 'required|integer',
            'pushTitle'    => 'required|string',
            'url'          => 'nullable|string',
            'summary'      => 'required|string',
            'isPopUp'      => 'required|integer',
            'presenceArea' => 'required|integer',
            'shopId'       => 'required|integer',
            'userIds'      => 'required|array',
        ]);

        if ($validator->fails()) {
            Log::warning("NsqSubSystemPopWindowCommand valid error:" . $validator->errors()->first(), $data);
            return false;
        }

        return true;
    }

    private function doHandle(array $data)
    {
        $notify = SystemNotifyService::save(
            false,
            $data['title'],
            $data['type'],
            $data['target'],
            '',
            $data['pushTitle'],
            $data['url'],
            SystemNotifyCenterModel::METHOD_TYPE_AUTOMATIC,
            $data['summary'],
            '',
            $data['isPopUp'],
            $data['presenceArea'],
            $data['shopId']
        );
        SystemNotifyService::recordLog($notify, '创建消息');
        SystemNotifyService::preSend($notify->id, $data['userIds']);
    }
}
